<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        // 方法1：截取数组求和
        // 最好的求和方法是reduce()
        // function arrSum(arr) {
        //     return arr.reduce((a, b) => a + b);
        // }

        // function getMax(arr, x) {
        //     let zuo = 0;
        //     let you = zuo + x;
        //     // console.log(you);//2
        //     let max = arrSum(arr.slice(zuo, you));
        //     // console.log(arr);//[4, 3, 6, 2, 8, 7, 9]
        //     for (; you <= arr.length; zuo++, you++) {
        //         const aaa = arrSum(arr.slice(zuo, you));
        //         max = Math.max(aaa, max);
        //     }
        //     return max;
        // }

        // const arr = [4, 3, 6, 2, 8, 7, 9];
        // console.log(getMax(arr, 2));

        // 方法2：纯算法思路，不需要借助数组的API
        function getMax2(arr,n){
            let max = 0;
            let sum = 0;
            for (let i=0;i<arr.length;i++){
                if(i === 0){
                    for(let j=0;j<n;j++){
                        max+=arr[j];
                    }
                    sum = max
                }else{
                    const arr1 = sum-arr[i-1]+arr[i-1+n];
                    if(arr1>max){
                        max=arr1;
                    }
                    sum=arr1
                }
            }
            return max;
        }
        const arr = [4, 3, 6, 2, 8, 7, 9];
        const res = getMax2(arr, 2);
        console.log(res);
    </script>
</body>

</html>